package com.lijinjiang.util;

import javax.swing.*;
import java.awt.*;

/**
 * @Description 弹出菜单工具类
 * @Author lijinjiang
 * @Date 2024-12-30 10:52
 */
public class PopupUtil {
    //点击按钮事件，继承该类的编辑器都要复写改代码
    public static void showPopupMenu(JComponent parent, JPopupMenu popupMenu, int count) {
        GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Rectangle maximumWindowBounds = graphicsEnvironment.getMaximumWindowBounds();
        double deskHeight = maximumWindowBounds.getHeight();//桌面高度（不包括任务栏）

        int height = 20 * count;
        if (height > 200) {
            height = 200;
        }
        Insets insets = popupMenu.getInsets();
        if (insets != null) {
            height = height + insets.top + insets.bottom;//需要添加popupMenu的insert大小
        }

        int width = parent.getWidth();
        popupMenu.setPreferredSize(new Dimension(width, height));
        int popupMenuBottom = parent.getLocationOnScreen().y + parent.getHeight() + height;

        if (deskHeight < popupMenuBottom) {//超出桌面高度显示在输入框上面
            popupMenu.show(parent, parent.getWidth() - width, -height);
        } else {
            popupMenu.show(parent, 0, parent.getHeight() + 2);
        }
    }
}
